<template>
  <div class="pagination">
    <!-- pageNo:当前页码 totalPages:总页码 total:总数 pageNum:连续值 -->
    <button
      :disabled="pageNo === startEndNum.start"
      @click="$emit('changePage', pageNo - 1)"
    >
      上一页
    </button>
    <button v-show="startEndNum.start > 1">1</button>
    <button v-show="startEndNum.start > 2">···</button>

    <button
      v-for="page in pageNumber"
      :key="page"
      :class="{ active: pageNo === page }"
      @click="$emit('changePage', page)"
    >
      {{ page }}
    </button>

    <button v-show="totalPages > startEndNum.end + 1">···</button>
    <button v-show="startEndNum.end < totalPages">{{ totalPages }}</button>
    <button
      :disabled="pageNo === startEndNum.end"
      @click="$emit('changePage', pageNo + 1)"
    >
      下一页
    </button>

    <button style="margin-left: 30px">共{{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "PageNumber",
  // pageNo:当前页码 totalPages:总页码 total:总数 pageNum:连续值
  props: ["pageNo", "totalPages", "total", "pageNum"],
  computed: {
    startEndNum() {
      // pageNo:当前页码 totalPages:总页数 pageNum:连续值
      const { pageNo, totalPages, pageNum } = this;
      let start = 0;
      let end = 0;
      // 如果连续值大于总页数
      if (pageNum > totalPages) {
        start = 1;
        end = totalPages;
      } else {
        start = pageNo - Math.floor(pageNum / 2);
        end = pageNo + Math.floor(pageNum / 2);
        // 如果起始值小于1
        if (start < 1) {
          start = 1;
          end = pageNum;
        }
        // 如果终止值大于总页数
        if (end >= totalPages) {
          end = totalPages;
          start = totalPages - pageNum + 1;
        }
      }
      return { start, end };
    },
    // 根据起始值排序出数组进行处理遍历生成
    pageNumber() {
      const arr = [];
      for (let i = 1; i <= this.startEndNum.end; i++) {
        if (i >= this.startEndNum.start) {
          arr.push(i);
        }
      }
      return arr;
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>